package com.hopes.bizz.enforcement.integral.listener.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.hopes.bizz.enforcement.common.constant.IntegralEventEnum;
import com.hopes.bizz.enforcement.hid.entity.RiskHidCheckTaskEntity;
import com.hopes.bizz.enforcement.hid.service.RiskHidCheckTaskService;
import com.hopes.bizz.enforcement.integral.bo.IntegralComputeBO;
import com.hopes.bizz.enforcement.integral.bo.IntegralEvent;
import com.hopes.bizz.enforcement.integral.entity.RiskIntegralRecordEntity;
import com.hopes.bizz.enforcement.integral.listener.IntegralEventSupport;
import com.hopes.bizz.enforcement.integral.service.EnfIntegralEventService;
import com.hopes.bizz.enforcement.integral.service.RiskIntegralRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author yumr
 * @ProjectName bizz
 * @Description 隐患检查任务积分统计
 * @time 2024/2/18 15:18
 */
@Slf4j
@Component("hid_check_integral")
public class HidCheckEventHandler extends IntegralEventSupport {

    private final RiskHidCheckTaskService riskHidCheckTaskService;

    protected HidCheckEventHandler(EnfIntegralEventService enfIntegralEventService,
                                   RiskIntegralRecordService riskIntegralRecordService, RiskHidCheckTaskService riskHidCheckTaskService) {
        super(enfIntegralEventService, riskIntegralRecordService);
        this.riskHidCheckTaskService = riskHidCheckTaskService;
    }

    @Override
    public void handler(IntegralEvent integralEvent) {
        // 1、业务Id
        final Long businessId = Optional.of(integralEvent).map(IntegralEvent::getBusinessId).orElse(null);
        final RiskHidCheckTaskEntity riskHidCheckTask = riskHidCheckTaskService.getById(businessId);
        if (ObjUtil.isNull(riskHidCheckTask)) {
            log.error("隐患检查任务数据不存在，业务标识：{}", businessId);
            return;
        }
        // 2、隐患检查任务积分事件
        final List<RiskIntegralRecordEntity> list = new ArrayList<>();
        final IntegralComputeBO integralComputeBO = new IntegralComputeBO(IntegralEventEnum.hid_check_integral, riskHidCheckTask, integralEventMap());
        final List<RiskIntegralRecordEntity> riskIntegralRecordList = integralComputeBO.computeIntegral();
        if (CollUtil.isNotEmpty(riskIntegralRecordList)) {
            list.addAll(riskIntegralRecordList);
        }
        final boolean b = saveIntegralRecordBatch(list);
        log.debug("隐患检查积分事件处理结果：{}", b);
    }
}
